// API配置文件
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'https://ai.tianjing.site/server/'

// 调试工具
const debug = {
  log: (...args) => {
    if (import.meta.env.DEV) {
      console.log('[API]', ...args)
    }
  },
  error: (...args) => {
    if (import.meta.env.DEV) {
      console.error('[API]', ...args)
    }
  }
}

// COS 配置
export const COS_CONFIG = {
  SecretId: 'AKIDoTAh8NOHxPdfT6WijX8GBuQinrhKjvwj',
  SecretKey: 'cbcT6VhiW6XntreHm7HG5jEYikfR4A6r',
  Region: 'ap-shanghai',
  Bucket: 'share-1259268558'
}

export const API_CONFIG = {
  BASE_URL: API_BASE_URL,
  ENDPOINTS: {
    // 用户认证相关
    LOGIN_BY_PHONE: '/auth/loginByPhone',
    REGISTER_BY_PHONE: '/auth/registerByPhone',

    // 数字人相关
    GET_UPLOAD_CREDENTIAL: '/aiAvatar/getUploadCredential',
    CREATE_AVATAR: '/aiAvatar/create',
    GET_AVATAR_LIST: '/aiAvatar/aiavatarList',
    GET_GENERATION_HISTORY: '/aiAvatar/videoAvatarList',
    
    // 个人数字人相关
    GET_MY_AVATARS: '/aiAvatar/myAvatars',
    UPDATE_AVATAR: '/aiAvatar/update',
    DELETE_AVATAR: '/aiAvatar/delete',
    CLONE_AVATAR: '/aiAvatar/clone',
    
    // 公共数字人相关
    GET_PUBLIC_AVATARS: '/aiAvatar/publicAvatars',
    GET_FEATURED_AVATARS: '/aiAvatar/featuredAvatars',
    GET_AVATAR_CATEGORIES: '/aiAvatar/categories',
    SEARCH_PUBLIC_AVATARS: '/aiAvatar/searchPublic',
    
    // 人种相关接口
    GET_ETHNICITY_LIST: '/ethnicity/list',
    GET_ETHNICITY_DETAIL: '/ethnicity/detail',
    
    // 数字人生成和处理
    GENERATE_AVATAR_VIDEO: '/aiAvatar/generateVideo',
    GET_AVATAR_DETAILS: '/aiAvatar/details',
    UPLOAD_AVATAR_ASSET: '/aiAvatar/uploadAsset',
    
    // 营销视频相关
    MARKETING_VIDEO: '/marketing/video',
    
    // 视频混剪相关
    VIDEO_MIX: '/video/mix',

    // 声音克隆相关
    VOICE_CLONE_SUBMIT: '/voiceClone/submit',
    VOICE_CLONE_LIST: '/voiceClone/list',
    VOICE_CLONE_DELETE: '/voiceClone/delete'
  }
}

// API请求函数
export const apiRequest = async (endpoint, options = {}) => {
  let url = `${API_BASE_URL}${endpoint}`
  // 处理 GET 请求的 params
  if (options.method === 'GET' && options.params && typeof options.params === 'object') {
    const searchParams = new URLSearchParams()
    Object.entries(options.params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, value)
      }
    })
    if (Array.from(searchParams).length > 0) {
      url += (url.includes('?') ? '&' : '?') + searchParams.toString()
    }
    // 删除 params，避免 fetch 报错
    delete options.params
  }
  debug.log('请求URL:', url)
  debug.log('请求选项:', options)

  try {
    debug.log('发起请求...')
    // 从 localStorage 获取 token
    const token = localStorage.getItem('token')
    
    const response = await fetch(url, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        // 如果有 token，添加到请求头
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        ...options.headers
      }
    })

    debug.log('响应状态:', response.status)
    
    // 如果返回 401，说明未登录或 token 过期
    if (response.status === 401) {
      // 清除 token
      localStorage.removeItem('token')
      // 跳转到登录页面
      window.location.href = '/login'
      throw new Error('未登录或登录已过期')
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    debug.log('响应数据:', data)
    return data
  } catch (error) {
    debug.error('请求失败:', error)
    throw error
  }
} 